﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace Eldert.IoT.RaspberryPi2.Ship
{
    /// <summary>
    /// Class used to retrieve and save settings to the settings file.
    /// </summary>
    internal class Settings
    {
        internal static bool SettingsFileUpdated;

        internal static string SettingsPath
        {
            get
            {
                var path = Path.Combine(Path.GetTempPath(), "Settings.xml");

                if (!File.Exists(path) || !SettingsFileUpdated)
                {
                    File.Copy("Settings.xml", path, true);
                    SettingsFileUpdated = true;
                }

                return path;
            }
        }

        private static XDocument _settingsDocument;
        private static readonly Dictionary<string, string> cache = new Dictionary<string, string>();

        private static XDocument SettingsDocument => _settingsDocument ?? (_settingsDocument = XDocument.Load(SettingsPath));

        public Settings()
        {
        }

        /// <summary>
        /// Get the setting with the specified name from the settings file.
        /// </summary>
        internal static string Read(string name)
        {
            if (!cache.ContainsKey(name))
            {
                cache.Add(name, SettingsDocument.Descendants().FirstOrDefault(e => e.Name.LocalName == name).Value);
            }

            return cache[name];
        }

        internal static void Write(string name, string value)
        {
            SettingsDocument.Descendants().FirstOrDefault(e => e.Name.LocalName == name).Value = value;

            using (var fileStream = new FileStream(SettingsPath, FileMode.Create))
            {
                SettingsDocument.Save(fileStream);
                fileStream.Flush();
            }

            if (cache.ContainsKey(name))
            {
                cache[name] = value;
            }
        }
    }
}
